package com.blog.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;

public class PinyinUtils {
    // 拼音格式
    private static final HanyuPinyinOutputFormat FORMAT = new HanyuPinyinOutputFormat();
    static {
        FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }
    // 获取中文词的全程
    public static String getFullPinyin(String chinese) {
        if(chinese == null || chinese.isEmpty()) {
            return "";
        }
        StringBuilder pinyin = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            // 只处理中文字符
            if (Character.toString(c).matches("[\\u4e00-\\u9fa5]")) {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, FORMAT);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        pinyin.append(pinyinArray[0]); // 取第一个拼音
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    // 忽略转换失败的字符
                }
            } else {
                // 非中文字符直接保留（如数字、字母）
                pinyin.append(c);
            }
        }
        return pinyin.toString().toLowerCase();
    }
    public static String getFirstLetterPinyin(String chinese) {
        if (chinese == null || chinese.isEmpty()) {
            return "";
        }
        StringBuilder firstLetters = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            if (Character.toString(c).matches("[\\u4e00-\\u9fa5]")) {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, FORMAT);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        // 取第一个拼音的首字母
                        firstLetters.append(pinyinArray[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    // 忽略转换失败的字符
                }
            } else {
                // 非中文字符直接保留首字符
                firstLetters.append(c);
            }
        }
        return firstLetters.toString().toLowerCase();
    }
}
